Good Inheritance and Bad Inheritance

Mark Leighton Fisher on 2008-05-23T17:04:52

Inheritance is evil, and must be destroyed is the slightly overwrought title of an article by BernieCode that, nonetheless, expresses an idea that I've long held — that most use of inheritance is better represented by either composition (HAS-A rather than IS-A) or by interface implementation/Perl 6 roles (ACT-AS rather than IS-A).

Inheritance works well for classes that are actually closely related (the canonical example of classes that represent the relationship of various species springs to mind here). What you often want (in my experience) are classes that can act in a certain way — for example, a horse and a dog that can act like a pet. The EventManager example in the article above is a particularly good example of where a Perl 6 role/Java interface/etc. solves a problem much more neatly and clearly than inheritance does.

By the way, Solving compositional problems with Perl 6 roles (which I just discovered) also looks like a pretty good resource on this topic, especially for us Perl users.


Don't have to wait for perl6, use Moose

jjn1056 on 2008-05-24T01:23:22

Moose makes all these very easy. First of all it supports classic inheritance, but clarifies the isa chain and adds a default base object (Moose::Object) that everything inherits from. You can also declare Roles and use attributes (Perl6 style attributes, not method/variable attributes) to compose functionality.

I highly recommend it.